# 导入必要的库
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 加载示例数据集
iris = load_iris()
X = iris.data
y = iris.target

# 数据分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 决策树分类
clf = DecisionTreeClassifier(max_depth=3)  # 设置最大深度为3以避免过拟合
clf.fit(X_train, y_train)

# 模型评估
y_pred = clf.predict(X_test)
print(f'Accuracy: {accuracy_score(y_test, y_pred)}')

# 打印决策树
from sklearn.tree import export_text
tree_rules = export_text(clf, feature_names=iris.feature_names)
print("\nDecision Tree Rules:\n", tree_rules)
